package com.szh.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.szh.common.utils.R;
import com.szh.gulimall.ware.feign.MemberFeignService;
import com.szh.gulimall.ware.vo.FareVo;
import com.szh.gulimall.ware.vo.MemberAddressVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;
import java.util.Objects;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.szh.common.utils.PageUtils;
import com.szh.common.utils.Query;
import com.szh.gulimall.ware.dao.WareInfoDao;
import com.szh.gulimall.ware.entity.WareInfoEntity;
import com.szh.gulimall.ware.service.WareInfoService;
import org.springframework.util.StringUtils;

@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {

    @Autowired
    private MemberFeignService memberFeignService;

    /**
     * 条件查询仓库列表，带分页展示
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.eq("id", key)
                    .or().like("name", key)
                    .or().like("address", key)
                    .or().like("areacode", key);
        }
        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    /**
     * 获取运费信息
     */
    @Override
    public FareVo getFare(Long addrId) {
        FareVo fareVo = new FareVo();
        R res = memberFeignService.addrInfo(addrId);
        MemberAddressVo memberAddressVo = res.getData("memberReceiveAddress", new TypeReference<MemberAddressVo>() {});
        if (Objects.nonNull(memberAddressVo)) {
            String phone = memberAddressVo.getPhone();
            String fare = phone.substring(phone.length() - 1);
            fareVo.setAddress(memberAddressVo);
            fareVo.setFare(new BigDecimal(fare));
            return fareVo;
        }
        return null;
    }
}